/**
 *
 * @author John Creecy
 */

package server;

import java.io.IOException;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ChatListener implements Runnable {

	public ChatListener() {
		//
	}

	public void run() {
		socketMonitor();
	}

	public void socketMonitor() {
		try {
			DatagramSocket serverSocket = new DatagramSocket(9876);
			Long timeStamp;
			while (true) {
				byte[] receiveData = new byte[1024];
				timeStamp = (long) (System.currentTimeMillis());
				try {
					DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
					serverSocket.receive(receivePacket);
					String packetData = new String(receivePacket.getData());
					InetAddress sourceIp = receivePacket.getAddress();
					String sourceIpString = sourceIp.toString();
					String ipAddress = sourceIpString.substring(1, sourceIp.toString().length());
					int sourcePort = receivePacket.getPort();
					BattleBarn.addProcessorTask(new ProcessorThread(packetData, ipAddress, sourcePort));
					BattleBarn.clientList.put(ipAddress, timeStamp);
				} catch (SocketException ex) {
					//Logger.getLogger(ChatListener.class.getName()).log(Level.SEVERE, null, ex);
					System.out.println("fail");
				} catch (IOException ex) {
					System.out.println("fail");
					//Logger.getLogger(ChatListener.class.getName()).log(Level.SEVERE, null, ex);
				}
			}
		} catch (SocketException ex) {
			System.out.println("fail");
			//Logger.getLogger(ChatListener.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
}
